<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生表单</title>
</head>
<script src="js/jquery-2.1.0.min.js"></script>
<body>
<!-- 查询表单 -->
<div align="center">
    <label for="searchName">姓名:</label>
    <input type="text" id="searchName" placeholder="请输入姓名">
    <label for="searchClass">班级:</label>
    <input type="text" id="searchClass" placeholder="请输入班级">
    <button onclick="searchStudents()">查询</button>
</div>
<div align="center">
    <h1>学生表单</h1>
    <table id="tb" border="2px">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>成绩</th>
            <th>班级</th>
            <th>操作</th>
        </tr>
    </table>
    <!-- 分页按钮 -->
    <div id="pagination" style="margin-top: 20px;">
        <!-- 分页按钮会动态生成 -->
    </div>
</div>
</body>
<script>
    function searchStudents(){
        let sname = $("#searchName").val(); // 获取姓名
        let className = $("#searchClass").val(); // 获取班级

        $.ajax({
            url: "/student/like",
            method: "get",
            data: {
                sname: sname,
                className: className
            },
            dataType: "json",
            success: function (ret) {
                if (ret.code == 2000) {
                    for (let i = 0; i < ret.data.length; i++) {
                        $("#tb").append(
                            "<tr>" +
                            "<td>" + ret.data[i].sid + "</td>" +
                            "<td>" + ret.data[i].sname + "</td>" +
                            "<td>" + ret.data[i].sage + "</td>" +
                            "<td>" + ret.data[i].score + "</td>" +
                            "<td>" + ret.data[i].className + "</td>" +
                            "<td>" + ret.data[i].className + "</td>" +
                            "<td>" +
                            "<button onclick='updateStudent(" + ret.data[i].sid + ")'>修改</button>" +
                            "<button onclick='deleteStudent(" + ret.data[i].sid + ")'>删除</button>" +
                            "</td>" +
                            "</tr>"
                        )
                    }
                } else {
                    alert("查询失败：" + ret.message);
                }
            },
            error: function () {
                alert("请求失败，请检查网络或服务器！");
            }
        });
    }
    let currentPage = 1; // 当前页
    const pageSize = 3; // 每页条数
    function loadData(page){
        $.ajax({
            url: "/student/allStudent",
            method: "get",
            dataType: "json",
            data: {
                page: page,
              pageSize: pageSize
            },
            success: function (ret) {
                console.log(ret.data)
                if (ret.code == 2000) {
                    // 清空表格
                    $("#tb").find("tr:not(:first)").remove();
                    for (let i = 0; i < ret.data.list.length; i++) {
                        $("#tb").append(
                            "<tr>" +
                            "<td>" + ret.data.list[i].sid + "</td>" +
                            "<td>" + ret.data.list[i].sname + "</td>" +
                            "<td>" + ret.data.list[i].sage + "</td>" +
                            "<td>" + ret.data.list[i].score + "</td>" +
                            "<td>" + ret.data.list[i].className + "</td>" +
                            "<td>" +
                            "<button onclick='updateStudent(" + ret.data.list[i].sid + ")'>修改</button>" +
                            "<button onclick='deleteStudent(" + ret.data.list[i].sid + ")'>删除</button>" +
                            "</td>" +
                            "</tr>"
                        )
                    }
                    // 更新分页
                    /**
                     * totalRecords：总记录数（用于计算总页数）。
                     * totalPages：总页数（通过后端计算后返回）。
                     * currentPage：当前页码。
                     */
                    generatePagination(ret.data.total, ret.data.pages, ret.data.pageNum);
                }
            }
        });
    }
    // 生成分页按钮
    function generatePagination(totalRecords, totalPages, currentPage) {
        let paginationHtml = "";

        if (currentPage > 1) {
            paginationHtml += "<button onclick='loadData(" + (currentPage - 1) + ")'>上一页</button>";
        }

        // 生成页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (i === currentPage) {
                paginationHtml += "<button style='font-weight: bold;'>" + i + "</button>";
            } else {
                paginationHtml += "<button onclick='loadData(" + i + ")'>" + i + "</button>";
            }
        }

        if (currentPage < totalPages) {
            paginationHtml += "<button onclick='loadData(" + (currentPage + 1) + ")'>下一页</button>";
        }

        // 将分页按钮添加到页面
        $("#pagination").html(paginationHtml);
    }

    // 页面加载时加载数据
    $(document).ready(function() {
        loadData(currentPage); // 加载初始页的数据
    });
    function deleteStudent(sid){
        $.ajax({
            url : "student/del?id="+sid,
            method : "get",
            dataType: "json",
            success: function (ret){
                if(ret.code == 2000){
                    alert(ret.msg)
                    location.reload(); // 刷新页面
                }
            }
        })
    }
    // 修改学生信息
    function updateStudent(sid) {
        // 1. 发送请求获取学生信息
        $.ajax({
            url: "/student/getStudentById?id=" + sid, // 注意URL拼接
            method: "get",
            dataType: "json",
            success: function (ret) {
                if (ret.code == 2000) {
                    // 2. 获取学生信息
                    let student = ret.data;

                    // 3. 弹出修改表单（可以使用模态框或弹出层）
                    let formHtml = `
                    <div id="updateForm" style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border: 1px solid #ccc;">
                        <h2>修改学生信息</h2>
                        <form id="studentForm">
                            <label>编号:</label>
                            <input type="text" id="sid" value="${student.sid}" readonly><br><br>
                            <label>姓名:</label>
                            <input type="text" id="sname" value="${student.sname}"><br><br>
                            <label>年龄:</label>
                            <input type="text" id="sage" value="${student.sage}"><br><br>
                            <label>成绩:</label>
                            <input type="text" id="score" value="${student.score}"><br><br>
                            <label>班级:</label>
                            <input type="text" id="className" value="${student.className}"><br><br>
                            <button type="button" onclick="submitUpdate()">提交</button>
                            <button type="button" onclick="closeForm()">取消</button>
                        </form>
                    </div>
                `;

                    // 4. 将表单添加到页面
                    $("body").append(formHtml);
                } else {
                    alert("获取学生信息失败！");
                }
            },
            error: function () {
                alert("请求失败，请检查网络或服务器！");
            }
        });
    }

    // 提交修改后的学生信息
    function submitUpdate() {
        // 1. 获取表单数据
        let sid = $("#sid").val();
        let sname = $("#sname").val();
        let sage = $("#sage").val();
        let score = $("#score").val();
        let className = $("#className").val();

        // 2. 发送修改请求
        $.ajax({
            url: "/student/updateStudent",
            method: "post",
            contentType: "application/json",
            data: JSON.stringify({
                sid: sid,
                sname: sname,
                sage: sage,
                score: score,
                className: className
            }),
            dataType: "json",
            success: function (ret) {
                if (ret.code == 2000) {
                    alert("修改成功！");
                    closeForm(); // 关闭表单
                    location.reload(); // 刷新页面
                } else {
                    alert("修改失败：" + ret.message);
                }
            },
            error: function () {
                alert("请求失败，请检查网络或服务器！");
            }
        });
    }

    // 关闭修改表单
    function closeForm() {
        $("#updateForm").remove();
    }

</script>
</html>